package 计算BMI指数;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class TestServer extends Application {
    @Override
    public void start(Stage primaryStage) {

        TextArea ta = new TextArea();

        Scene scene = new Scene(new ScrollPane(ta), 450, 200);
        primaryStage.setTitle("TestServer");  // Set the stage title
        primaryStage.setScene(scene);  // Place the scene in the stage
        primaryStage.show();  // Display the stage

        new Thread(() -> {
            try{
            ServerSocket serverSocket = new ServerSocket(8000);
            Platform.runLater(() ->
                    ta.appendText("TestServer started at " + new Date() + '\n'));
            // 监听连接请求
            Socket socket = serverSocket.accept();

            // 创建数据输入和输出流
            DataInputStream inputFromClient = new DataInputStream(
                    socket.getInputStream());
            DataOutputStream outputToClient = new DataOutputStream(
                        socket.getOutputStream());

            while (true){
                double height = inputFromClient.readDouble();
                double weight = inputFromClient.readDouble();
                double bmi = (height*height)/weight;

                outputToClient.writeDouble(bmi);

                Platform.runLater(() -> {
                    ta.appendText("Weight received from client: " + weight + '\n');
                    ta.appendText("Height received from client: " + height + '\n');
                    ta.appendText("bmi is: " + bmi + '\n');
                });
            }
        } catch (IOException ex) {
                ex.printStackTrace();
            }
        }).start();

    }

    public static void main(String[] args) {
        launch(args);
    }
}
